package com.tanhua.dubbo.api.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.api.MessageApi;
import com.tanhua.dubbo.enums.CommentType;
import com.tanhua.dubbo.mapper.AnnouncementMapper;
import com.tanhua.dubbo.pojo.Announcement;
import com.tanhua.dubbo.pojo.Comment;
import com.tanhua.dubbo.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService(version = "1.0.0")
@Slf4j
public class MessageApiImpl implements MessageApi {
    @Autowired
    AnnouncementMapper announcementMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public PageInfo queryMessageList(Long userId,Integer page, Integer pageSize,CommentType type) {

        //构建返回对象
        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);

        CommentType commentType;
        switch (type){
            case LIKE:
                commentType=CommentType.LIKE;
                break;
            case COMMENT:
                commentType = CommentType.COMMENT;
                break;
            case LOVE:
                commentType = CommentType.LOVE;
                break;
            default:
                return pageInfo;

        }

        //根据用户id查询他的圈子有谁点赞
        PageRequest pageRequest = PageRequest.of(page-1,pageSize);
        Query query = Query.query(Criteria.where("publishUserId")
                .is(userId).and("commentType")
                .is(commentType.getType())).with(pageRequest)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Comment> likeList = this.mongoTemplate.find(query, Comment.class);

        if(ObjectUtil.isEmpty(likeList)){
            return pageInfo;
        }
        pageInfo.setRecords(likeList);


        return pageInfo;
    }

    @Override
    public IPage<Announcement> queryAnnouncementsList(Integer page, Integer pageSize) {
        //新建查询
        QueryWrapper<Announcement> queryWrapper = new QueryWrapper<>();
        //根据发布日期倒序排序
        queryWrapper.orderByDesc("created");
        //分页查询
        Page<Announcement> pageQuery = new Page<>(page, pageSize);
        //mybatis-plus查询数据库
        IPage<Announcement> announcementIPage = this.announcementMapper.selectPage(pageQuery, queryWrapper);
        return announcementIPage;
    }
}
